﻿namespace BEGDC.CC.Web.Workflow
{
    #region Using Directives

    using System;
    using System.Collections;
    using System.Data;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using BL.Common;
    using BL.UserManagement;
    using Utility.Castle;
    using Utility.Extensions;

    #endregion

    /// <summary>
    ///   Summary description for SelectEngineerForm.
    /// </summary>
    public class SelectEngineerForm : Page
    {
        private static string departments = string.Empty;
        protected DropDownList Branch;
        protected DropDownList Department;
        protected TextBox NameBox;
        protected RegularExpressionValidator RegularExpressionValidator1;
        protected RequiredFieldValidator RequiredFieldValidator1;
        protected Button Search;
        protected HtmlTableCell TD_Choose;
        protected HtmlTableCell TD_Information;
        protected HtmlTableRow TR_Branch;
        protected DataTable dataTable;
        protected DataView dataView;
        protected HtmlSelect engineerName;
        protected Literal litScript;
        protected Button btnOK;
        protected Button btnCancel;

        //protected System.Web.UI.WebControls.RegularExpressionValidator RegularExpressionValidator1;
        private string type = string.Empty;
        //private string selfID = string.Empty;

        /// <summary>
        /// </summary>
        private string _selfID
        {
            get
            {
                return this.ViewState["_selfID"] == null ? string.Empty : Convert.ToString(this.ViewState["_selfID"]);
            }
            set
            {
                this.ViewState["_selfID"] = value;
            }
        }

        private void Page_Load(object sender, EventArgs e)
        {
            departments = this.Request.QueryString["Depts"];
            this.type = this.Request.QueryString["type"];
            this._selfID = this.Request.QueryString["self"];

            this.btnOK.Attributes.Add("onclick", "javascript:Do_Comfirm()");
            this.btnCancel.Attributes.Add("onclick", "javascript:Do_Cancel()");

            if (!string.IsNullOrEmpty(this._selfID))
            {
                this.type = "AC";
            }

            if (!this.IsPostBack)
            {
                if (departments.Length != 0)
                {
                    this.Department.Enabled = false;
                    this.Branch.Enabled = false;
                    //InitialSearch();
                }
                else
                {
                    this.BuildBizGroup();
                    this.BuildBizUnit();
                    //InitialSearch();
                }
            }
            try
            {
                this.TR_Branch.Visible = false;
                this.TD_Choose.InnerHtml = "&nbsp;Please choose (请选择):";

                //dataTable = userService.GetEngineerByType(type);
                //dataView = dataTable.DefaultView;

                this.litScript.Text = "<script>window.Form1.btnOK.value='OK';";
                this.litScript.Text += "window.Form1.btnCancel.value='Cancel'</script>";
            }
            catch
            {
            }
        }

        #region Build DropDown

        private void BuildBizGroup()
        {
            var userService = AppContainer.Instance[ServiceConst.UserService] as IUser;
            this.Department.DataSource = userService.GetBusinessGroupList();
            this.Department.DataTextField = "DepartmentCode";
            this.Department.DataValueField = "ID";
            this.Department.DataBind();
            this.Department.Items.Insert(0, new ListItem(string.Empty, "-1"));
            this.Department.SelectedIndex = 0;
        }

        private void BuildBizUnit()
        {
            //			ListItem li = this.Department.SelectedItem;
            //			if(li!=null && li.Text!=string.Empty)
            //			{
            //				IUser userService = AppContainer.Instance[ServiceConst.UserService] as IUser;
            //				this.Branch.DataSource = userService.GetBusinessUnitList(li.Text);
            //				this.Branch.DataTextField = "DepartmentCode";
            //				this.Branch.DataValueField = "ID";
            //				this.Branch.DataBind();
            //				this.Branch.Items.Insert(0,new System.Web.UI.WebControls.ListItem(string.Empty,"-1"));
            //				this.Branch.SelectedIndex = 0;
            //			}
            //			else
            //			{
            //				this.Branch.Items.Clear();
            //			}
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///   Required method for Designer support - do not modify
        ///   the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Department.SelectedIndexChanged += this.Department_SelectedIndexChanged;
            this.Search.Click += new System.EventHandler(this.Search_Click);
            this.Load += this.Page_Load;
        }

        #endregion

        #region Select Index Change

        private void Department_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BuildBizUnit();
        }

        #endregion

        #region Search Click

        protected void Search_Click(object sender, EventArgs e)
        {
            string dept = string.Empty;
            string bran = string.Empty;
            string name = string.Empty;
            string sql = string.Empty;

            if (departments != string.Empty)
            {
                sql = ParseDept();
            }
            else
            {
                if (this.Department.SelectedItem != null && this.Department.SelectedValue != "-1")
                {
                    dept = this.Department.SelectedValue;
                }
                //				if(this.Branch.SelectedItem!=null)
                //				{
                //					bran = this.Branch.SelectedItem.Value+string.Empty;
                //				}
                if (dept.Length != 0)
                {
                    sql += " empl.Department=" + dept;
                }
                //				if(bran!=string.Empty)
                //				{
                //					if(sql!=string.Empty)
                //					{
                //						sql += "and ";
                //					}
                //					sql+= " empl.Department="+bran;
                //				}
            }

            name = this.NameBox.Text;

            if (name.IsNotNullOrWhiteSpace())
            {
                if (sql.Length != 0)
                {
                    sql += " and ";
                }

                sql += "NameEN like '%" + name + "%'";
            }

            if (sql.Length != 0)
            {
                sql += " and ";
            }

            sql += " isactived = 1";

            this.DoDisplayResults(sql);

            //			if ((name == null) || (name == string.Empty))
            //			{
            //				this.TD_Information.InnerHtml = "&nbsp;&nbsp;&nbsp;System list all engineers";
            //			}
            //			else
            //			{
            //				//dataView.AllowDelete = true;
            //				dataView.RowFilter = "EnglishName like '%"+name+"%'";
            //
            //				//dataView.RowStateFilter = DataViewRowState.ModifiedCurrent;
            //				if (dataView.Count == 1)
            //				{
            //					this.TD_Information.InnerHtml = "&nbsp;&nbsp;&nbsp;System found \"<b>"+name+"</b>\".";
            //				}
            //				else
            //				{
            //					this.TD_Information.InnerHtml = "&nbsp;&nbsp;&nbsp;System found more than one \"<b>"+name+"</b>\".";
            //				}
            //			}
        }

        #endregion

        #region Initial Search

        private static string ParseDept()
        {
            string sql = " Brahch in (";
            string[] dept = departments.Split(',');
            for (int i = 0; i < dept.Length; i++)
            {
                if (i == (dept.Length - 1))
                {
                    sql += "'" + dept[i] + "'";
                }
                else
                {
                    sql += "'" + dept[i] + "',";
                }
            }
            sql += ") ";
            return sql;
        }

        private void InitialSearch()
        {
            if (departments != string.Empty)
            {
                string sql = ParseDept();
                this.DoDisplayResults(sql);
            }
            else
            {
                this.DoDisplayResults(string.Empty);
            }
        }

        #endregion

        #region Do Display Results

        private void DoDisplayResults(string sql)
        {
            this.engineerName.Items.Clear();

            var userService = AppContainer.Instance[ServiceConst.UserService] as IUser;
            this.dataTable = userService.GetEngineerByType(this.type, sql);
            this.dataView = this.dataTable.DefaultView;

            //dataView.RowFilter = sql;

            if (this.dataTable == null || this.dataTable.Rows.Count == 0)
            {
                return;
            }

            foreach (var item in
                from DataRow row in this.dataTable.Rows where string.IsNullOrEmpty(this._selfID) || this._selfID != row[1].ToString() select new ListItem("[" + row[2] + "]" + row[0], row[0] + "|" + row[1] + "|" + row[3] + "|" + row[4] + "|" + row[5] + "|" + row[6]))
            {
                this.engineerName.Items.Add(item);
            }
            this.engineerName.SelectedIndex = 0;
        }

        #endregion
    }
}